<?php

class UserController extends AdminController {

    protected $layout = 'admin::layouts.master';
    /**
     * Display a listing of the resource.
     *
     * @return Response
     */
    public function index() {

        $users = DB::table('users')
            ->where('id', '<>', Auth::User()->id)
            ->where('status', '<>', 1)
            ->paginate(5);

        return View::make('admin::user.index', array('users' => $users))->with('title', 'List user');
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return Response
     */
    public function create() {
        $user = new User();

        return View::make('admin::user.create', array('user' => $user))->with('title', 'Create user');
    }


    /**
     * Store a newly created resource in storage.
     *
     * @return Response
     */
    public function store() {
        $user = User::find(Input::get('id'));

        if (Request::isMethod('post')) {
            if (Input::get('id')) {
                $rules = array(
                    'first_name' => 'required|min:3|max:50',
                    'last_name'  => 'required|min:3|max:50'
                );
            } else {
                $rules = array(
                    'first_name' => 'required|min:3|max:50',
                    'last_name'  => 'required|min:3|max:50',
                    'email'      => 'required|email|unique:users', // make sure the email is an actual email
                    'password'   => 'required|alphaNum|min:3' // password can only be alphanumeric and has to be greater than 3 characters
                );
            }

            $validator = Validator::make(Input::all(), $rules);

            if ($validator->fails()) {

                return Redirect::to($this->packageAdmin.'/admin/create')->withErrors($validator)->withInput();// send back all errors to the login form
            } else {

                if ($user) {
                    $user->first_name = Input::get('first_name');
                    $user->last_name  = Input::get('last_name');

                    if ($user->update(array('first_name', 'last_name', 'email'))) {
                        return Redirect::route('view', array('id' => $user->id))->with('success', 'User saved in successfully');
                    }
                } else {
                    $user = new User();
                    $user->first_name = Input::get('first_name');
                    $user->last_name  = Input::get('last_name');
                    $user->email      = Input::get('email');

                    if ($user->save()) {
                        return Redirect::to($this->packageAdmin.'/admin/list')->with('success', 'User saved in successfully');
                    }
                }
            }
        }

        return View::make('user.create');
    }


    /**
     * Display the specified resource.
     *
     * @return Response
     */
    public function show() {
        return View::make('admin::user.profile');
    }

    /**
     * Update the specified resource in storage.
     * @param  int  $id
     * @return Response
     */
    public function update($id) {
        if ($id) {
            $user = DB::table('users')->find($id);

            if ($user) {
                return View::make('admin::user.create')->with('user', $user);
            }
        }

        return Redirect::to($this->packageAdmin.'/admin/list')->with('flash_error', 'User id '. $id. ' not found.');
    }

    /**
     * View information for user
     *
     * @param  int  $id
     * @return Response
     */
    public function view($id) {
        if ($id) {
            $user = DB::table('users')->find($id);

            if ($user) {
                return View::make('admin::user.view', array('user' => $user))->with('title', $user->first_name .'&nbsp'. $user->last_name);
            } else {
                return Redirect::to('dtu/admin/user')->with('flash_error', 'User id '. $id. ' not found.');
            }
        }

        return Redirect::to('/');
    }


    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return Response
     */
    public function destroy($id) {
        $user = User::find($id);

        if ($user) {
            if ($user->status == 1) {
                $user->status = 0;
            } else {
                $user->status = 1;
            }

            if ($user->update(array('status'))) {
                return Redirect::route('user')->with('flash_error', 'User id '. $id. ' deleted.');
            }
        }

        return Redirect::route('user')->with('flash_error', 'User id '. $id. ' not found.');
    }

    /**
     * @return \Illuminate\View\View
     */
    public function login() {

        if (Auth::check()) {
            return Redirect::route('dtu/admin')->with('success', 'You have logged in successfully');
        }

        if (Request::isMethod('post')) {
            // validate the info, create rules for the inputs
            $rules = array(
                'email' => 'required|email', // make sure the email is an actual email
                'password' => 'required|alphaNum|min:3' // password can only be alphanumeric and has to be greater than 3 characters
            );

            // run the validation rules on the inputs from the form
            $validator = Validator::make(Input::all(), $rules);

            // if the validator fails, redirect back to the form
            if ($validator->fails()) {
                return Redirect::to($this->packageAdmin.'/admin/login')
                    ->withErrors($validator)// send back all errors to the login form
                    ->withInput(Input::except('password')); // send back the input (not the password) so that we can repopulate the form
            } else {

                // create our user data for the authentication
                $userData = array(
                    'email' => Input::get('email'),
                    'password' => Input::get('password')
                );

                // attempt to do the login
                if (Auth::attempt($userData)) {
                    // validation successful!
                    // redirect them to the secure section or whatever
                    return Redirect::to($this->packageAdmin.'/admin')->with('success', 'You have logged in successfully');
                } else {
                    return Redirect::route('login')->with('flash_error', 'Your username/password combination was incorrect.')->withInput();
                }
            }
        } else {
            return View::make('admin::user.login')->with('title', 'Login');
        }
    }

    /**
     * @return \Illuminate\Http\RedirectResponse
     */
    public function logout() {
        if (Auth::check()){
            Auth::logout();
        }

        return Redirect::route('login')->with('flash_notice', 'You are successfully logged out.');
    }
}
